# -*- coding: utf-8 -*-
import arcpy

# arcpy.env.workspace = arcpy.GetParameterAsText(0)
arcpy.env.overwriteOutput = True
XZDW_clip = arcpy.GetParameterAsText(0)
DLTB_Clip = arcpy.GetParameterAsText(1)

XZDW_LIST = arcpy.ListFields(XZDW_clip)
XZDW_FIELD = []
for each in XZDW_LIST:
    XZDW_FIELD.append(each.name)
if "KD" in XZDW_FIELD and "KCBL" in XZDW_FIELD:
    arcpy.AddField_management(DLTB_Clip, "KCMJ", "DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")
    arcpy.AddField_management(DLTB_Clip, "KCXZDWMJ", "DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")
    arcpy.AddField_management(XZDW_clip, "长度", "DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")
    arcpy.CalculateField_management(XZDW_clip,"长度","!shape.length!","PYTHON_9.3")
    arcpy.AddField_management(DLTB_Clip,"MJ", "DOUBLE", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")
    arcpy.CalculateField_management(DLTB_Clip, "MJ", "!shape.area!", "PYTHON_9.3")
    with arcpy.da.UpdateCursor(DLTB_Clip,["MJ","KCMJ","ZLDWDM","TBBH","KCXZDWMJ"]) as cursor:
        for row in cursor:
            with arcpy.da.SearchCursor(XZDW_clip,["长度","KD","KCBL"], where_clause="([KCTBDWDM1] = \""+row[2]+"\" and [KCTBBH1] = \""+ row[3]+"\") or ([KCTBDWDM2] = \""+row[2]+"\" and [KCTBBH2] =\""+ row[3]+"\")" ) as xzdw_cursor:
                mj = 0
                for xzdw in xzdw_cursor:

                    mj+= (xzdw[0]*xzdw[1]*xzdw[2])
            row[1] = round(mj,2)
            row[4] = round((row[0] - row[1]),2)
            if row[4] < 0:
                row[4] = 0
            cursor.updateRow(row)
else:
    arcpy.AddMessage("线状地物图层缺少字段!")
